import { Role } from '../models';
import { Op } from "sequelize";
import { getDefaultCorporate } from './corporate_entities';


export async function getDefaultNobodyRole(entityId){
    return await Role.findOrCreate({
        where: {CorporateEntityId: entityId, isNobody: true},
        defaults: {
            createdAt: new Date(), updatedAt: new Date(), 
            isLogined: false, owner: false,
        }, 
    })
}

export async function getDefaultLoginedRole(entityId){
    return await Role.findOrCreate({
        where: {CorporateEntityId: entityId, isLogined: true},
        defaults: {
            createdAt: new Date(), updatedAt: new Date(),
            owner: false, isNobody: false,
        }, 
    })
}

export async function getDefaultAdminRole(entityId){
    return await Role.findOrCreate({
        where: {CorporateEntityId: entityId, owner: true},
        defaults: {
            createdAt: new Date(), updatedAt: new Date(),
            isNobody: false,  isLogined: false,
        }, 
    })
}


export async function findOrCreateOne(roleName, entityId){
    
    return await Role.findOrCreate({where: {name: roleName},
        defaults: {createdAt: new Date(), updatedAt: new Date(), CorporateEntityId: entityId}, 
    })
}

export async function createDefaultRolesForEntity(entityId){
    const nobody = await getDefaultAdminRole(entityId);
    const logined = await getDefaultLoginedRole(entityId);
    const admin = await getDefaultAdminRole(entityId);
    return {
        nobody,
        logined,
        admin
    }
}

export async function findOrCreateMany(roleNames, entityId){
    for (let index = 0; index < roleNames.length; index++) {
        const roleName = roleNames[index];
        await findOrCreateOne(roleName, entityId);
    }
}

export async function setDefaultRoles(){
    //isNoBody: true, isLogined: true, isOnwer: false
    //每个实体的nobody isLogined, isOwner 是必须存在的
    const entity = await getDefaultCorporate();
    return await findOrCreateMany(
    ["未登录用户", "已登录用户", "超级管理员"], entity.id
    );
}
